package cn.com.generaldata.os.service.indicator_evaluation.incr_analysis;

 

 
import java.io.BufferedReader;
import java.math.BigDecimal;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.namespace.QName;

import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.entity.Record;
import org.nutz.dao.sql.Criteria;
import org.nutz.lang.random.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import cn.com.generaldata.jsme_indicator_system.entity.IndicatorEvaluation;
import cn.com.generaldata.jsme_indicator_system.util.Constants;
import cn.com.generaldata.os.pojo.IndicatorEvaluationResult;
import cn.com.generaldata.os.service.impl.SendReportService;
import cn.com.generaldata.os.service.indicator_evaluation.IndicatorEvaluationCalculateService;
import cn.com.generaldata.os.util.CacheManager;
import cn.com.generaldata.os.vo.IndicatorAccountVO;
 

/**
 * 海洋经济生产总值ARIMA评估指标计算类.
 */
public class GDOceanEconomyCalculateService extends IndicatorEvaluationCalculateService {
	private static final QName SERVICE_NAME = new QName("org.cis.api.GopCalculate", "GopCalculateImplService");

	private static Logger log = LoggerFactory.getLogger(GDOceanEconomyCalculateService.class);

	private CacheManager cacheManager = CacheManager.getInstance();

	private String wsURL = cacheManager.getGlobalConfig("gDOceanEconomyWsUrl");
		
	/** 定期年份 */
	private int baseYear = 2001;
	 
	@Override
	protected Double calculate(IndicatorEvaluation indicator, IndicatorAccountVO indicatorAccountVO) {
		System.out.println("wsURL.result=" + wsURL);	 
		Double result = null;
	//	String basePath = GDOceanEconomyCalculateService.class.getResource("").getPath().substring(1).replace("/", "\\\\");
		if (indicator.getSection() == Constants.INDICATOR_LEVEL_PROVINCE) {
			 //获取结果数据最大年
			 
			result = calculateProvinceResult(indicator, indicatorAccountVO);
			
		} else if (indicator.getSection() == Constants.INDICATOR_LEVEL_CITY) {
			// 市指标没确定先保留
		}
		return new BigDecimal(result).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
	}
	
	/**
	 * 计算江苏省进出口总额增长率评估指标计算类.
	 * 
	 * @param indicator
	 * @param indicatorAccountVO
	 * @return
	 */
	private Double calculateProvinceResult(IndicatorEvaluation indicator, IndicatorAccountVO indicatorAccountVO) {
		
	 
		Double val = null;
		BufferedReader br=null ;
		//S cal=null;
		try {
			
			Criteria cri = getIndicatorDataCri(indicatorAccountVO, indicatorAccountVO.getYear(), indicator.getId());
			Double indicatorVal_res = getEvaluationIndicatorValue(cri);
			//TBL_INDICATOR_EVALUATION_RES 当前年度无值,就取T_INDICATOR_INPUT表数据
			if (indicatorVal_res==null || indicatorVal_res.equals("")) {
				String paths = GDOceanEconomyCalculateService.class.getResource("").getPath().substring(1).replace("/", "\\\\");
				Double indicatorVal = getInputOrAccountingIndicatorValue(indicatorAccountVO,
						indicatorAccountVO.getYear(), indicator.getReference());
				//T_INDICATOR_INPUT表无值,就预测计算当前年的新值
				if ( indicatorVal==null || indicatorVal.equals("")) {
					//获取当前年的前一年和基准年之间的所有海洋生产总值数据
					double[]  res = getProsperityIndicatorData(indicatorAccountVO,indicator);
					//预测处理类
				//	cal = new S();
					/*Object[] result = cal.PREDICTION_Gedp(1, res);
					MWNumericArray r = (MWNumericArray) result[0];
					int index = indicatorAccountVO.getYear() - baseYear;
					if (index < 0) {
						return null;
					}*/
					// matlab 数组从1开始,获取最后的一年度的预测值
				//	val = cal.calculateGop(res);
					// -y 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 -gdp 587.50 672.86 792.19 928.42 1018.61 1287 1873.50 2114.50 2717.40 3550.90 4253.10 4723 5288.04 5849.36 6407.95
					/*String result="";
					Process proc = Runtime.getRuntime().exec("python  "+paths+"predict_test1.py"+res);
					//Process proc = Runtime.getRuntime().exec(args);
					proc.waitFor();
					br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
					
					String lineStr;
					while ((lineStr = br.readLine()) != null) {
						result += lineStr;
					}
			        System.out.println("-----"+result);
			        if(StringUtils.isNotBlank(result)){
			        	val =Double.parseDouble(result);
			        }*/
					val = getValue(res);
				}else{
					
					val=indicatorVal;
				}
			}else{
				
				val=indicatorVal_res;
			}
			
			
		} catch (Exception e) {
			log.error("调用python计算海洋经济生产总值指标预测值错误", e);
		}  
		return val;
	}

	/**
	 * 获取相关数据.
	 * 
	 * @param indicatorAccountVO
	 * @param indicatorNames
	 * @return
	 */
/*	private String getProsperityIndicatorData(IndicatorAccountVO indicatorAccountVO,IndicatorEvaluation indicator) {
		int yearLength = indicatorAccountVO.getYear() - baseYear;
		StringBuffer sBuffer = new StringBuffer(" -gdp");
		StringBuffer yBuffer = new StringBuffer(" -y");
		for (int i = 0; i < yearLength; i++) {
			int year = baseYear+i;
			Criteria cri = getIndicatorDataCri(indicatorAccountVO, year, indicator.getId());
			Double indicatorVal_res = getEvaluationIndicatorValue(cri);
			//TBL_INDICATOR_EVALUATION_RES 当前年度无值,就取T_INDICATOR_INPUT表数据
			if (indicatorVal_res==null || indicatorVal_res.equals("")) {
				Double indicatorVal = getInputOrAccountingIndicatorValue(indicatorAccountVO,
						year, indicator.getReference());
				//T_INDICATOR_INPUT表无值,就预测计算当前年的新值
				if ( indicatorVal==null || indicatorVal.equals("")) {
					BufferedReader br=null ;
					try {
						//如果此年度无值就进行预测，然后存入数据库，在返回值进行下一年度预测，最后一值到选择条件的前一年度。
						String paths = GDOceanEconomyCalculateService.class.getResource("").getPath().substring(1).replace("/", "\\\\");
						String result="";
						String res = yBuffer.toString()+sBuffer.toString();
						Process proc = Runtime.getRuntime().exec("python  "+paths+"predict_test1.py"+res);
						proc.waitFor();
						br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
						String lineStr;
						while ((lineStr = br.readLine()) != null) {
							result += lineStr;
						}
				        System.out.println("-----"+result);
				        if(StringUtils.isNotBlank(result)){
				        	//val =Double.parseDouble(result);
				        	sBuffer.append(" "+Double.parseDouble(result));//此年度无值
							yBuffer.append(" "+year);
							saveData(indicatorAccountVO,Double.parseDouble(result),indicator.getId(),year);
							//存储数据库
				        }
					}catch(Exception e){
						if (br !=null) {
							try {
								br.close();
							} catch (IOException e0) {
								log.error("调用python计算海洋经济生产总值指标预测值错误", e0);
							}
						}
					}finally {
						if (br !=null) {
							try {
								br.close();
							} catch (IOException e1) {
								log.error("调用python计算海洋经济生产总值指标预测值错误", e1);
							}
						}
					}
					
				}else{
					sBuffer.append(" "+indicatorVal);
					yBuffer.append(" "+year);
				}
			}else{
				sBuffer.append(" "+indicatorVal_res);
				yBuffer.append(" "+year);
			}	
		}
		return yBuffer.toString()+sBuffer.toString();
	}*/
	
	
	private double[] getProsperityIndicatorData(IndicatorAccountVO indicatorAccountVO,IndicatorEvaluation indicator) {
		int yearLength = indicatorAccountVO.getYear() - baseYear;
	//	StringBuffer sBuffer = new StringBuffer(" -gdp");
	//	StringBuffer yBuffer = new StringBuffer(" -y");
		double[] value = new double[yearLength];
		for (int i = 0; i < yearLength; i++) {
			int year = baseYear+i;
			Criteria cri = getIndicatorDataCri(indicatorAccountVO, year, indicator.getId());
			Double indicatorVal_res = getEvaluationIndicatorValue(cri);
			//TBL_INDICATOR_EVALUATION_RES 当前年度无值,就取T_INDICATOR_INPUT表数据
			if (indicatorVal_res==null || indicatorVal_res.equals("") || indicatorVal_res == 0.0) {
				Double indicatorVal = getInputOrAccountingIndicatorValue(indicatorAccountVO,
						year, indicator.getReference());
				//T_INDICATOR_INPUT表无值,就预测计算当前年的新值
				if ( indicatorVal==null || indicatorVal.equals("")) {
					 
					try {
					//	S cal = new S();
						double val = 0.0;
						/*Object[] result = cal.PREDICTION_Gedp(1, value);
						MWNumericArray r = (MWNumericArray) result[0];
						Double val = r.getDouble(1);*/
						
						double[] newArray = removeZeroArray(value);
						
					//	val = cal.calculateGop(newArray);
						val = getValue(newArray);
						
				        if(val != 0){
				        	//val =Double.parseDouble(result);
				        //	sBuffer.append(" "+Double.parseDouble(result));//此年度无值
						//	yBuffer.append(" "+year);
				        	value[i]=val;
				        	val = new BigDecimal(val).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
							saveData(indicatorAccountVO,val,indicator.getId(),year);
							//存储数据库
				        }
					}catch(Exception e){
						 e.printStackTrace();
					} 
					
				}else{
					//sBuffer.append(" "+indicatorVal);
					//yBuffer.append(" "+year);
					value[i]=indicatorVal;
				}
			}else{
				//sBuffer.append(" "+indicatorVal_res);
				//yBuffer.append(" "+year);
				value[i]=indicatorVal_res;
			}	
		}
		return value;//yBuffer.toString()+sBuffer.toString();
	}

	//保存中间空缺的预测值
	private void saveData(IndicatorAccountVO indicatorAccountVO,double result,Integer id,Integer year) {
		IndicatorEvaluationResult ier = new IndicatorEvaluationResult();
		ier.setIndicatorId(id);
		ier.setYearTime(indicatorAccountVO.getYearTime());
		ier.setIndicatorValue(result);
		ier.setTimeType(indicatorAccountVO.getTimeType());
		ier.setYear(year);
		ier.setAreaId(indicatorAccountVO.getAreaId());
		Criteria cri = getIndicatorEvaluationDataCri(ier);

		Record record = dao.fetch("tbl_indicator_evaluation_res", cri);
		if (record != null) {
			dao.clear("tbl_indicator_evaluation_res", cri);
		}
		saveEvaluationResult(ier);
	}
	
	private Criteria getIndicatorEvaluationDataCri(IndicatorEvaluationResult indicatorAccountVO) {
		Criteria cri = Cnd.cri();
		cri.where().and("indicator_id", "=", indicatorAccountVO.getIndicatorId());
		cri.where().and("time_type", "=", indicatorAccountVO.getTimeType());
		cri.where().and("year_time", "=", indicatorAccountVO.getYearTime());
		cri.where().and("area_id", "=", indicatorAccountVO.getAreaId());
		cri.where().and("year", "=", indicatorAccountVO.getYear());
		return cri;
	}
	
	
	private void saveEvaluationResult(IndicatorEvaluationResult ier) {
		// 保存新记录
		Chain chain = Chain.make("id", R.UU16());
		chain.add("indicator_id", ier.getIndicatorId());
		chain.add("area_id", ier.getAreaId());
		chain.add("time_type", ier.getTimeType());
		chain.add("year_time", ier.getYearTime());
		chain.add("year", ier.getYear());
		chain.add("indicator_value", ier.getIndicatorValue());
		dao.insert("tbl_indicator_evaluation_res", chain);
	}
	
	private double[] removeZeroArray(double[] val){
		
		
		int len = 0;
		
		for (double v : val){
			if (v!=0.0){
				len++;
			}
		}
		
		double[] newArray = new double[len];
		
		for (int i = 0, j = 0; i < val.length; i++){
			if (val[i]!=0.0){
				if(String.valueOf(val[i]).indexOf(".")<0){
					newArray[j] = Double.parseDouble(String.valueOf(val[i]));
				}else{
					newArray[j] = val[i];
				}
				j++;
			}			
		}		
		return newArray;
	}
	public  double getValue(double[] ass) {
		 double _calculateGop__return =0d;
		   try {
			  // double[] ass={587.50,672.86,792.19,928.42,1018.61,1287.0,1873.50,2114.50,2717.40,3550.90,4253.10,4723.0,5288.04,5849.36,6407.95};
			   URL wsdlURL = new URL(wsURL);
			   GopCalculateImplService ss = new GopCalculateImplService(wsdlURL, SERVICE_NAME);
		       GopCalculate port = ss.getGopCalculateImplPort(); 
		       List<Double> list = new ArrayList<Double>();  
		        for (int i=0; i<ass.length; i++) { 
		        	if(ass[i]!=0.0){
		        		list.add(ass[i]);
		        	}
		        }
		        _calculateGop__return = port.calculateGop(list);
			} catch (Exception e) {
				e.printStackTrace();
				 
			}
			   return _calculateGop__return;
		}
}
